import React, { useState, useCallback, createContext, ReactNode } from 'react';
import { View } from 'react-native';
import Toast from './MyToast';
import { ToastOptions, ToastType, ToastInstance } from './types';

interface ToastItem extends ToastOptions {
  id: string;
  visible: boolean;
}

export const ToastContext = createContext<ToastInstance | null>(null);

interface ToastProviderProps {
  children: ReactNode;
}

export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => {
  const [toasts, setToasts] = useState<ToastItem[]>([]);

  const hideToast = useCallback((id: string) => {
    setToasts(prevToasts =>
      prevToasts.map(toast =>
        toast.id === id ? { ...toast, visible: false } : toast,
      ),
    );
    // 动画完成后从队列中删除
    setTimeout(() => {
      setToasts(prevToasts => prevToasts.filter(toast => toast.id !== id));
    }, 300);
  }, []);

  const show = useCallback(
    (options: ToastOptions): string => {
      const id = Date.now().toString();
      const newToast: ToastItem = { ...options, id, visible: true };

      setToasts(prevToasts => [...prevToasts, newToast]);

      // 如果非loading且设置了duration，自动关闭
      const displayDuration = options.duration ?? 1500; // 使用统一的默认值5秒
      if (options.type !== 'loading' && displayDuration > 0) {
        setTimeout(() => {
          hideToast(id);
        }, displayDuration);
      }

      return id;
    },
    [hideToast],
  );

  const hide = useCallback(
    (id: string) => {
      hideToast(id);
    },
    [hideToast],
  );

  const hideAll = useCallback(() => {
    setToasts(prevToasts =>
      prevToasts.map(toast => ({ ...toast, visible: false })),
    );
    setTimeout(() => {
      setToasts([]);
    }, 300);
  }, []);

  const createTypeSpecificShow = useCallback(
    (type: ToastType) => {
      return (
        message: string,
        options: Omit<ToastOptions, 'message' | 'type'> = {},
      ) => {
        return show({ message, type, ...options });
      };
    },
    [show],
  );

  const toastApi: ToastInstance = {
    show,
    hide,
    hideAll,
    success: createTypeSpecificShow('success'),
    error: createTypeSpecificShow('error'),
    warning: createTypeSpecificShow('warning'),
    info: createTypeSpecificShow('info'),
    loading: createTypeSpecificShow('loading'),
  };

  return (
    <ToastContext.Provider value={toastApi}>
      {children}
      <View
        pointerEvents="box-none"
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          zIndex: 9999,
        }}
      >
        {toasts.map(toast => (
          <Toast
            key={toast.id}
            {...toast}
            onClose={() => hideToast(toast.id)}
          />
        ))}
      </View>
    </ToastContext.Provider>
  );
};
